<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\admin\model\AuthDepartment;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Http;
use think\Config;
use think\Debug;
use think\Session;
use app\admin\model\Sale as SaleModel;


/**
 * 周销售
 */
class Sale extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];

    protected $noNeedRight = ['*'];

    public $up_time;
    public $end_time;
    public $week;


    public function _initialize(){

        parent::_initialize();
        //获取默认值
        $this->config = \app\admin\model\Sale::config(); //获取配置 周销售
        $this->auth = \app\admin\library\Auth::instance();
        $this->week = date('W');//当前第几周
        $this->page = date("W", mktime(0, 0, 0, 12, 28, date("Y")));
        $this->up_time = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"))));
        $this->end_time = strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))));
    }

    public function login()
    {
        header('Access-Control-Allow-Credentials:true');
        if(!$this->auth->isLogin())
        {
            $app = Factory::work($this->config);
            $token = $app->access_token->getToken();//获取企业微信token
            $code = $this->request->request('code');
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
            $user = json_decode(Http::get($url),true);
            $this->auth->IndexLogin($user['UserId']);//登录
        }
//        $this->success('登录成功',$this->auth->getUserinfo());
        return redirect($this->request->domain().'/sale');
    }

    /**
     * 首页
     */
    public function index()
    {
//        $this->auth->IndexLogin('001');
        $user = $this->auth->getUserinfo();
        header('Access-Control-Allow-Credentials:true');
        // 检测是否需要验证登录
        if (!$this->auth->isLogin()){
            return redirect($this->request->domain().'/api/sale/oauth');
        }
       if($this->request->isPost())
       {
           $time = 0;
           $pageTime = 0;
           $week = 0;
           $where = $this->SaleCheck();
           if($this->request->request('page'))
           {
               $page = $this->request->request('page');
               if($page > $this->week)
               {
                   $pageTime = ($page - $this->week) * (7 * 24 * 60 * 60);
                   $week = $this->week + ($page - $this->week);
                   $time = date("m.d",$this->up_time + $pageTime).'-'.date("m.d",$this->end_time + $pageTime);
                   $up_time = $this->up_time + $pageTime;
                   $end_time = $this->end_time + $pageTime;
               }
               if($page < $this->week && $page != 0 && $page != -1)
               {
                   $pageTime  = ($this->week - $page) * (7 * 24 * 60 * 60);
                   $week = $this->week - ($this->week - $page);
                   $time = date("m.d",$this->up_time - $pageTime).'-'.date("m.d",$this->end_time - $pageTime);
                   $up_time = $this->up_time - $pageTime;
                   $end_time = $this->end_time - $pageTime;
               }
               if($page == $this->week)
               {
                   $week = $this->week;
                   $time = date("m.d",$this->up_time).'-'.date("m.d",$this->end_time);
                   $up_time = $this->up_time;
                   $end_time = $this->end_time;
               }
               if($page >= ($this->page + 1) ||  $page == -1)
               {
                   $week = 1;
                   $pageTime = ($this->week * (7 * 24 * 60 * 60)) - (7 * 24 * 60 * 60);
                   $time = date("m.d",$this->up_time - $pageTime).'-'.date("m.d",$this->end_time - $pageTime);
                   $up_time = $this->up_time - $pageTime;
                   $end_time = $this->end_time - $pageTime;
               }
           }else{
               $week = $this->week;
               $time = date("m.d",$this->up_time).'-'.date("m.d",$this->end_time);
               $up_time = $this->up_time;
               $end_time = $this->end_time;
           }
           $list = SaleModel::field('id,region,name,grade,department_id,uptime,endtime,count(*) as ronda,sum(hot_num) as hot_num,sum(video_num) as video_num,sum(book_num) as book_num')
               ->where([
                   'endtime' => ['>=',$up_time],
                   'uptime' => ['<=',$end_time],
               ])
               ->where($where)
               ->group('department_id')->select();
           $list =  $this->listArr(collection($list)->toArray());
           $this->success('请求成功',['list'=>$list,'week'=>$week,'time'=>$time]);
       }
        return redirect($this->request->domain().'/sale');
    }

    public function listArr($list)
    {
        $arr = [14=>null,15=>null,16=>null,17=>null];
        foreach ($list as $k=>$value)
        {
            $arr[$value['region']][$k] = $value;
        }
        return $arr;
    }


    public function oauth()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

    /**
     * 添加
     */
    public function add()
    {
        header('Access-Control-Allow-Credentials:true');
//        $this->auth->IndexLogin('ceshi');
        $user = $this->auth->getUserinfo();
        if(!$region = getChild(explode(',',$user['department']))) $this->error(__('查不到所在的分区'), null, 200);
        if(!$this->auth->check('finance/extract/week/index')) $this->error(__('You have no permission'), null, 200);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $saleModel = new SaleModel();
            $sale = $saleModel->ApiAdd($params,$user,$region,$this->up_time,$this->end_time);
            $res = pushMsgText(SaleModel::config(),'text',['content'=>$sale['msg']],Config::get('site.userid'),0,Config::get('site.department'),Config::get('site.tag'));
            $this->success('添加成功！');
        }
        $this->error(__('请使用POST请求！'));
    }



    /**
     * @param $region 分区ID
     * @param $dept   部门ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ListDepartment($region,$dept,$page)
    {
        header('Access-Control-Allow-Credentials:true');
//        $this->auth->IndexLogin('001');
        $where = $this->SaleCheck();
        if($page > $this->week)
        {
            $pageTime = ($page - $this->week) * (7 * 24 * 60 * 60);
            $up_time = $this->up_time + $pageTime;
            $end_time = $this->end_time + $pageTime;
        }
        if($page < $this->week && $page != 0 && $page != -1)
        {
            $pageTime  = ($this->week - $page) * (7 * 24 * 60 * 60);
            $up_time = $this->up_time - $pageTime;
            $end_time = $this->end_time - $pageTime;
        }
        if($page == $this->week || $page == 0)
        {
            $up_time = $this->up_time;
            $end_time = $this->end_time;
        }
        if($page >= ($this->page + 1) ||  $page == -1)
        {
            $pageTime = ($this->week * (7 * 24 * 60 * 60)) - (7 * 24 * 60 * 60);
            $up_time = $this->up_time - $pageTime;
            $end_time = $this->end_time - $pageTime;
        }
        $list = SaleModel::where([
            'region'=>$region,
            'department_id'=>$dept,
            'endtime' => ['>=',$up_time],
            'uptime' => ['<=',$end_time],
            ])
            ->where($where)
            ->select();
        foreach ($list as &$value)
        {
            $value['lecturer'] = Admin::userName($value['lecturer']);
            $value['host'] = Admin::userName($value['host']);
            $value['finance'] = Admin::userName($value['finance']);
            $value['video'] =unserialize($value['video']);
            $value['book'] = unserialize($value['book']);
            $value['school_book'] = unserialize($value['school_book']);
            $value['meeting_book'] = unserialize($value['meeting_book']);
        }
        $this->success('列表',$list);
    }


    /**
     * 获取查询条件
     * @return string
     */
    public function SaleCheck()
    {
        /*
         *  添加：公司财务
            查看：刘总、刘副总、路鑫鑫、刘亚娟、刘倩然、路丽梅 后台配置
            查看：分公司总经理、副总、讲师，大区经理  财务 自己分区的
         */
        $userid = explode('|',Config::get('site.userids'));
        $user = $this->auth->getUserinfo();
        if(in_array($user['userid'],$userid)) //查看固定人员所有数据
        {
            return ' 1=1 ';
        }
        if(in_array(3,$user['group_id']))  //是否是财务
        {
            return " finance='{$user['userid']}' ";
        }
        if(in_array(11,$user['group_id'])) //是否是主持人
        {
            return " host='{$user['group_id']}' ";
        }
        if(in_array(10,$user['group_id'])) //是否是讲师
        {
            return " lecturer='{$user['userid']}' ";
        }
        return $where = "region in ({$user['department']}) or department_id in ({$user['department']})";

    }

    /**
     * @param $id
     */
    public function edit($id)
    {
        header('Access-Control-Allow-Credentials:true');
        if($this->request->isPost())
        {
            $row = $this->request->request('row/a');
            $saleModel = new SaleModel();
            $data = $saleModel->where('id', $id)->find();
            $data = $saleModel->StringMerging(unserialize($data->video)); //$data['num'];
            $row['video_num'] = $data['num'] + $row['book_total'] + $row['office_total'];
            if($saleModel->allowField(['book_total','office_total','video_num'])->save($row, ['id' => $id]))
            {
                $this->success('修改成功！',$row['video_num']);
            }
            $this->error(['修改失败']);
        }
    }

    /**
     * 获取 10讲师 2财务 11主持人数据
     */
    public function PublicData()
    {
        header('Access-Control-Allow-Credentials:true');
        $finance = AuthGroupAccess::alias('a')
        ->join('admin b', 'a.userid = b.userid', 'LEFT')
        ->field("a.userid as userid,b.username as username")
        ->where('a.group_id','3')
        ->select();//获取财务
        $host = AuthGroupAccess::alias('a')
            ->join('admin b', 'a.userid = b.userid', 'LEFT')
            ->field("a.userid as userid,b.username as username")
            ->where('a.group_id','11')
            ->select();//主持人
        $lecturer = AuthGroupAccess::alias('a')
            ->join('admin b', 'a.userid = b.userid', 'LEFT')
            ->field("a.userid as userid,b.username as username")
            ->where('a.group_id','10')
            ->select();//讲师
        $this->success('添加成功！',['lecturer'=>$lecturer,'finance'=>$finance,'host'=>$host]);
    }
    /**
     * 自动回复消息接口
     */
    public function Api()
    {
        $config = SaleModel::config();
        $app = Factory::work($config);
        $app->server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    return '';
                    break;
                default:
                    return '收到其它消息';
                    break;
            }
        });
        $response = $app->server->serve();
        $response->send();exit;
    }
}
